<?php


namespace paySdk\core;


use Exception;

class PaySdk
{
    protected $app;

    private $log_path;

    static private $available_log_type_arr = ['warning', 'info', 'error'];

    static private $available_mode = ["testing", "production"];

    public $mode = "testing";

    /**
     * BaseClient constructor.
     * @param Container $app
     * @throws Exception
     */
    public function __construct(Container $app)
    {
        $today = date('Y-m-d', time());
        $this->app = $app;
        $this->log_path = realpath(dirname(__FILE__)) . "/../log/{$today}.log";

        if (isset($this->app->params['mode']) && ! in_array($this->app->params['mode'], static::$available_mode))
            throw new Exception("非法mode参数");
        else if (isset($this->app->params['mode']))
            $this->mode = $this->app->params['mode'];
    }
    /**
     * @param mixed $log_path
     */
    public function setLogPath($log_path)
    {
        $this->log_path = $log_path;
    }

    /**
     * @param string $msg
     * @param string $type
     * @throws Exception
     */
    public function log(string $msg, string $type = 'info')
    {
        if (! $msg)
            throw new Exception("日志消息不能为空");
        if (! in_array($type, static::$available_log_type_arr))
            throw new Exception("无效日志类型");

        $tracer_arr = debug_backtrace();
        $tracer_info = array_shift($tracer_arr);
        $line = $tracer_info['line'];
        $function = $tracer_arr[0]['function'];
        $class = $tracer_arr[0]['class'];

        $time = "[" . date('Y-m-d H:i:s', time()) . "]";
        $msg = "{$time} - {$type} - {$class} - {$function} - {$line}: {$msg}\r\n";

        file_put_contents($this->log_path, $msg, FILE_APPEND);
    }

    /**
     * 0x转高精度数字
     * @param $hex
     * @return int|string
     */
    protected function hex2dec($hex)
    {
        $dec = 0;
        $len = strlen($hex);
        for ($i = 1; $i <= $len; $i++) {
            $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
        }
        return round($dec,0);
    }
}